//
//  CJImagesTableViewController3.m
//  CJFoundationDemo
//
//  Created by ciyouzen on 2016/3/26.
//  Copyright © 2016年 dvlproad. All rights reserved.
//

#import "CJImagesTableViewController3.h"
#import <SDWebImage/SDWebImage.h>
#import "CQTSNetImagesUtil.h"
#import "CQTSLocImagesUtil.h"
#import "CJImagesTableViewCell1.h"

@interface CJImagesTableViewController3 () <UITableViewDataSource, UITableViewDelegate> {
    
}
@property (nonatomic, strong) NSOperationQueue *queue;

@end

@implementation CJImagesTableViewController3

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = NSLocalizedString(@"一定要加载大图列表的时候(查看重用效果)", nil); //知识点:使得tabBar中的title可以和显示在顶部的title保持各自
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    //[tableView registerClass:[CJImagesTableViewCell1 class] forCellReuseIdentifier:@"cell"];
    tableView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0]; // #f5f5f5
//    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mas_topLayoutGuide).mas_offset(20);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(4*150);
    }];
    tableView.estimatedRowHeight = 150;
//    tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView = tableView;
    
    
    NSMutableArray *sectionDataModels = [[NSMutableArray alloc] init];
    
    //ImagesTable
    {
        CQDMSectionDataModel *sectionDataModel = [[CQDMSectionDataModel alloc] init];
        sectionDataModel.theme = @"ImagesTable";
        NSMutableArray<CQTSNetImageDataModel *> *imageDataModels = [CQTSNetImagesUtil __getTestNetImageDataModelsWithCount:100 randomOrder:NO];
        [sectionDataModel.values addObjectsFromArray:imageDataModels];
        
        [sectionDataModels addObject:sectionDataModel];
    }
    
    self.sectionDataModels = sectionDataModels;
    
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.name = @"this is a queue";
    queue.maxConcurrentOperationCount = 6;
    self.queue = queue;
    
    
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    //让tableView准备好后，再显示
//        [self loadShowCells];
//    });
    
    // 注意：scrollToRowAtIndexPath时候，scrollViewDidEndDragging 和 scrollViewDidEndDecelerating 这两个代理不会响应。
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 2秒后异步执行这里的代码...
        NSLog(@"测试使用scrollToRowAtIndexPath时候的效果");
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    });
}

#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionDataModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    CQDMSectionDataModel *sectionDataModel = [self.sectionDataModels objectAtIndex:section];
    NSArray *dataModels = sectionDataModel.values;
    
    return dataModels.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CQDMSectionDataModel *sectionDataModel = [self.sectionDataModels objectAtIndex:indexPath.section];
    NSArray *dataModels = sectionDataModel.values;
    CQTSNetImageDataModel *moduleModel = [dataModels objectAtIndex:indexPath.row];
    

    // 小知识点：cellForRowAtIndexPath调用次数太多，static 保证只创建一次reuseID，提高性能
    static NSString *reuseCellID = @"cell";
    CJImagesTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:reuseCellID];
    // 小知识点：从缓存池中取相应identifier的Cell并更新数据，如果没有，才开始alloc新的Cell，并用identifier标识Cell。
    if (cell == nil) {
        cell = [[CJImagesTableViewCell1 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseCellID];
    }
    cell.titleNameLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row];
    cell.messageTipLabel.text = moduleModel.name;
    
    NSURL *imageURL = [NSURL URLWithString:moduleModel.imageUrl];
//    UIImage *placeholderImage = [CQTSLocImagesUtil cjts_placeholderImage01];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [cell.iconImageView sd_setImageWithURL:imageURL placeholderImage:placeholderImage];
//    });
    
    if (tableView.dragging || tableView.decelerating) {
        [cell setImageModel:moduleModel shouldLoadImage:NO withIndexPath:indexPath];
    } else {
        NSLog(@"非滑动时候的cellForRowAtIndexPath:%ld", indexPath.row);
        [cell setImageModel:moduleModel shouldLoadImage:YES withIndexPath:indexPath];
    }
        
    
//    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
//        NSLog(@"%@ %@", moduleModel.name, [NSThread currentThread]);
//        sleep(3);
////        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
//
//            dispatch_async(dispatch_get_main_queue(), ^{
////                NSLog(@"%@", moduleModel.name);
//                cell.iconImageView.image = image;
//            });
//
////        });
//    }];
//
//
//
//    @synchronized (self) {
////        for (NSOperation *pendingOperation in self.queue.operations) {
////            [pendingOperation addDependency:operation];
////        }
//        [self.queue addOperation:operation];
//    }
    
//@synchronized (self) {
//        NSLog(@"%ld", self.queue.operations.count);
//        if (self.queue.operationCount > 6) {
////                for (NSOperation *op in self.queue.operations) {
////                    if (op.isExecuting) {
////                        [op cancel];
////                    }
////                }
//            [self.queue.operations[0] cancel];
//        }
//
//        [self.queue addOperation:operation];
//    }
    
//    @synchronized (self) {
//
//        NSLog(@"%ld", self.queue.operations.count);
//        if (self.queue.operationCount > 6) {
//            NSLog(@"取消");
//            NSMutableArray *operations = self.queue.operations.mutableCopy;
//            [operations removeObjectAtIndex:0];
//
//            [self.queue cancelAllOperations];
//            NSLog(@"%ld", self.queue.operations.count);
//            for (NSOperation *operation2 in operations) {
//                [self.queue addOperation:operation2];
//            }
////            [self.queue addOperations:operations waitUntilFinished:NO];
////            [self.queue.operations[0] cancel];
//        }
//
//
//
//        [self.queue addOperation:operation];
//    }
    
     
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"didSelectRowAtIndexPath = %zd %zd", indexPath.section, indexPath.row);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CQDMSectionDataModel *sectionDataModel = [self.sectionDataModels objectAtIndex:indexPath.section];
    NSArray *dataModels = sectionDataModel.values;
    CQTSNetImageDataModel *moduleModel = [dataModels objectAtIndex:indexPath.row];
    
    [self execModuleModel:moduleModel];
}


- (void)execModuleModel:(CQTSNetImageDataModel *)moduleModel {
    
}


#pragma mark - 监听滚动事件
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSLog(@"----%d",decelerate);
    
    if (!decelerate) {
       //滑动时,加载占位图
       [self loadShowCells];
   }
}

#pragma mark - 监听滚动事件
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self loadShowCells];
}

#pragma mark - 加载Cell中网络头像图片
- (void)loadShowCells {
    NSArray *array = [self.tableView indexPathsForVisibleRows];
    for (NSIndexPath *indexPath in array) {
        CJImagesTableViewCell1 * cell = (CJImagesTableViewCell1 *)[self.tableView cellForRowAtIndexPath:indexPath];
        
        CQDMSectionDataModel *sectionDataModel = [self.sectionDataModels objectAtIndex:indexPath.section];
        NSArray *dataModels = sectionDataModel.values;
        CQTSNetImageDataModel *moduleModel = [dataModels objectAtIndex:indexPath.row];
        [cell setImageModel:moduleModel shouldLoadImage:YES withIndexPath:indexPath];
    }
}
    

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
